package sk.fritz.megafonsms.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Random;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public class HttpPostRequest {
	HttpConnection connection;
	OutputStreamWriter writer = null;

	protected void connect() throws IOException {
		if (writer == null)
			writer = new OutputStreamWriter(connection.openOutputStream(),
					"UTF-8");
	}

	protected void write(String s) throws IOException {
		connect();
		writer.write(s);
	}

	protected void newline() throws IOException {
		connect();
		write("\r\n");
	}

	protected void writeln(String s) throws IOException {
		connect();
		write(s);
		newline();
	}

	private static Random random = new Random();

	protected static String randomString() {
		return Long.toString(random.nextLong(), 36);
	}

	String boundary = "---------------------------" + randomString()
			+ randomString() + randomString();

	private void boundary() throws IOException {
		write("--");
		write(boundary);
	}

	public HttpPostRequest(String url) throws IOException {
		this.connection = (HttpConnection) Connector.open(url);
		connection.setRequestMethod(HttpConnection.POST);
		connection.setRequestProperty("Content-Type",
				"multipart/form-data; boundary=" + boundary);
		connection.setRequestProperty("Connection", "close");
	}

	private void writeName(String name) throws IOException {
		newline();
		write("Content-Disposition: form-data; name=\"");
		write(name);
		write("\"");
	}

	public void setParameter(String name, String value) throws IOException {
		boundary();
		writeName(name);
		newline();
		newline();
		writeln(value);
	}


	public void setParameter(String name, Object object) throws IOException {
		setParameter(name, object.toString());
	}

	
	public void setParameters(Hashtable parameters) throws IOException {
		if (parameters == null)
			return;
		Enumeration en = parameters.keys();
		while (en.hasMoreElements()) {
			String name = (String) en.nextElement();
			Object value = parameters.get(name);
			setParameter(name, value);
		}
	}

	
	public void setParameters(Object[] parameters) throws IOException {
		if (parameters == null)
			return;
		for (int i = 0; i < parameters.length - 1; i += 2) {
			setParameter(parameters[i].toString(), parameters[i + 1]);
		}
	}

	
	public String post() throws IOException {
		boundary();
		writeln("--");
		writer.close();
		
		InputStream istrm = null;
		try {
			int response = connection.getResponseCode();
			if (response == HttpConnection.HTTP_OK) {
				istrm = connection.openInputStream();
				if (istrm == null) {
					throw new IOException("Cannot open HTTP InputStream, aborting");
				}

				return new String(Util.readFromInputStream(istrm));
			} else if (response == HttpConnection.HTTP_MOVED_PERM){
				return "Moved to " + connection.getHeaderField("Location");;
			} else {
				throw new IOException(connection.getResponseMessage());
			}
		} finally {
			if (istrm != null)
				istrm.close();
			if (connection != null)
				connection.close();
		}
	}

	
	public String post(Hashtable parameters) throws IOException {
		setParameters(parameters);
		return post();
	}

	
	public String post(Object[] parameters) throws IOException {
		setParameters(parameters);
		return post();
	}

	public String post(String name, Object value) throws IOException {
		setParameter(name, value);
		return post();
	}


	public static String post(String url, Hashtable parameters)
			throws IOException {
		return new HttpPostRequest(url).post(parameters);
	}
}
